import WxValidate from '../../utils/WxValidate';
const common = require('../../js/config.js');
const App = getApp()
var countdown = 60;
const app = getApp();

var settime = function (that) {
  // clearTimeOut(timer)
  if (countdown == 0) {
    that.setData({
      codeIsCanClick: true
    })
    countdown = 60;
    //clearTimeOut(timer)
    return;
  } else {
    that.setData({
      codeIsCanClick: false,
      last_time: countdown
    })
    countdown--;
  }
  var timer = setTimeout(function () {
    settime(that)
  }, 1000
  )
}
Page({
  data: {
    securityNumbers: '',
    codeIsCanClick: true,
    SureCanClicks: false,
    phone: '',
    updateOrsubmit: 'submit',
    disabled: false,
    checked: true,
    form: {
      email: '',
      baseName: '',
      position: '',
      mechanism: '',
      address: '',
      code: '',
      mechPhone: '',
    },
    files: [],
    showTopTips: false,
    fromChange: 0,
    pathUrl: ''
  },
  onChange(event) {
    this.setData({
      checked: event.detail
    });
    console.log(event.detail)
  },
  tosomewhere(e){
    const pagesd = e.currentTarget.dataset.where
    wx.navigateTo({
      url: '../'+pagesd+'/'+pagesd,
    })
  },
  experience(){
    wx.showToast({
      title: "暂未开放此模块",
      icon: "none",
      duration: 1000,
      mask: false,
    })
  },
  chooseImage: function (e) {
    let _this = this
    if (_this.data.fromChange == 0) {
      console.log('请添加名片')
    } else {
      var that = this;
      wx.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'], // 可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album', 'camera'], // 可以指定来源是相册还是相机，默认二者都有
        success: function (res) {

          // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
          that.setData({
            files: that.data.files.concat(res.tempFilePaths)
          });
          const tempFilePaths = res.tempFilePaths
          wx.uploadFile({
            url: common.formal + '/report/uploadReport.form',
            filePath: tempFilePaths[0],
            name: 'reportFile',
            header: { 'content-type': 'multipart/form-data' },
            method: 'POST',
            formData: {
              'masterCatalog': 'vrCard',
              'pId': that.data.objectId,
              'delImgurls': that.data.pathUrl,
              'fileTag': 'cd-wh',
              'weight': 300,
              'height': 300,
              'fileType': '1-2'
            },
            success(res) {
              console.log(res.data)
              var strings = res.data
              var jsonObj = JSON.parse(res.data);//转换为json对象
              for (var i = 0; i < jsonObj.length; i++) {
                console.log(jsonObj[i].pathUrl);
                _this.setData({
                  pathUrl: jsonObj[i].pathUrl
                })//取json中的值
              }
              const data = res.data
              //do something
            }
          })
        }
      })

    }
    // wx.request({
    //   url: common.formal + '/createId.form',
    //   method: 'get',
    //   success: function (result) {
    //     _this.setData({
    //       pid: 'base_' + result.data.data.objectId
    //     })
    //     console.log(_this.data.pid)
    //   }
    // })

  },
  inputTyping: function (e) {
    var newPhone = e.detail.value
    var that = this;
    that.setData({
      phone: newPhone
    });
  },
  securityNums: function (e) {
    var that = this;
    var phone = that.data.phone
    console.log(phone)
    if (phone != '') {
      settime(that)
      wx.request({
        // url: common.domain+'/getCode.form',
        url: common.formal + '/user/getCode.form',
        data: {
          test: common.test,
          phone: that.data.phone
        },
        method: 'get',
        success: function (json) {
          console.log(json);
          that.setData({
            SureCanClicks: true
          })
        },
        fail: function (json) {
          wx.showToast({
            title: json.data,
          })
        }
      });
    } else {
      wx.showToast({
        title: '无效的手机号！',
      })
    }

  },
  previewImage: function (e) {
    wx.previewImage({
      current: e.currentTarget.id, // 当前显示图片的http链接
      urls: this.data.files // 需要预览的图片http链接列表
    })
  },
  submitForm(e) {
    const params = e.detail.value

    console.log(params)

    // 传入表单数据，调用验证方法
    if (!this.WxValidate.checkForm(params)) {
      const error = this.WxValidate.errorList[0]
      this.showModal(error)
      return false
    }
    this.showModal({
      msg: '提交成功',
    })
  },
  checkPhone: function () {
    var that = this
    var phone = that.data.phone
    if (!(/^1[3456789]\d{9}$/.test(phone))) {
      wx.showToast({
        title: '请输入有效的手机号',
        icon: 'none',
        duration: 2000
      })
      return false;
    } else {
      that.securityNums()
    }
  },
  checkEmail: function (e) {
    var email = e.detail.value
    var _this = this
    var reg = /^([a-zA-Z]|[0-9])(\w|\-)+@[a-zA-Z0-9]+\.([a-zA-Z]{2,4})$/;
    if (reg.test(email)) {
      _this.setData({
        disabled: false
      })
    } else {
      wx.showToast({
        title: '邮箱格式错误，请重新输入',
        icon: 'none',
        duration: 2000
      })
      _this.setData({
        disabled: true
      })
    }
  },
  initValidate() {
    // 验证字段的规则
    const rules = {
      baseName: {
        required: true,
        rangelength: [2, 10],
      },
      phone: {
        required: true,
        phone: true,
      },
      mechanism: {
        // required: true,
        rangelength: [2, 15],
      },
      code: {
        required: true,
        minlength: [6],
      },
      position: {
        required: true,
        rangelength: [2, 11]
      },
      email: {
        // required: false,
        email: true,
        rangelength: [2, 31]
      },
      address: {
        // required: true,
        rangelength: [2, 15],
      },


    }

    // 验证字段的提示信息，若不传则调用默认的信息
    const messages = {
      baseName: {
        required: '请输入姓名',
        rangelength: '请输入2-4个汉字'
      },
      phone: {
        required: '请输入手机号',
        phone: '请输入正确的手机号',
      },
      mechanism: {
        // required: '请输单位名',
        rangelength: '请合理控制您的单位名称长度'

      },
      code: {
        required: '请输入验证码',
        minlength: '请输入正确的验证码'
      },
      position: {
        required: '请输入岗位',
        rangelength: '请控制您的岗位字数'
      },
      email: {
        // required: '请输入邮箱',
        email: '请输入正确的邮箱',
        rangelength: '请控制您的邮箱长度'
      },
      address: {
        // required: '请输入单位地址',
        rangelength: '请控制您的单位地址长度'
      },


    }

    // 创建实例对象 
    this.WxValidate = new WxValidate(rules, messages)
  },
  submitForm(e) {
    var that = this
    console.log(e.detail.value.updateOrsubmit)
    const params = e.detail.value
    console.log(params)
    console.log(that.data.pathUrl)
    // 传入表单数据，调用验证方法
    if (!this.WxValidate.checkForm(params)) {
      const error = this.WxValidate.errorList[0]
      this.showModal(error)
      return false
    }
    if (e.detail.value.updateOrsubmit == 'submit') {
      console.log('haha')
      that.setData({
        subdisabled: true
      })
      wx.request({
        url: common.formal + '/addBaseCard.form',
        data: {
          baseName: e.detail.value.baseName,
          phone: e.detail.value.phone,
          mechanism: e.detail.value.mechanism,
          position: e.detail.value.position,
          code: e.detail.value.code,
          unionid: that.data.unionid,
          baseId: that.data.pid,
          avatarUrl: that.data.pathUrl
        },
        method: 'get',
        success: function (requestRes) {
          console.log(requestRes)
          if (requestRes.data.status == '2') {
            wx.showToast({
              title: requestRes.data.msg,
              icon: 'none',
              during: 2000
            })
            that.setData({
              subdisabled: false
            })
          } else {
            wx.reLaunch({
              url: '/pages/trans/trans'
            })
          }
        },
        fail: function () {
        },
        complete: function () {
        }
      })
    } else {

      wx.request({
        url: common.formal + '/updateBaseCard.form',
        data: {
          baseName: e.detail.value.baseName,
          email: e.detail.value.email,
          phone: e.detail.value.phone,
          mechanism: e.detail.value.mechanism,
          address: e.detail.value.address,
          position: e.detail.value.position,
          mechPhone: e.detail.value.mechPhone,
          code: e.detail.value.code,
          unionid: that.data.unionid,
          baseId: that.data.objectId,
          avatarUrl: that.data.pathUrl,
          imageUrl: that.data.imageUrl
        },
        method: 'get',
        success: function (requestRes) {
          console.log(requestRes)
          console.log(requestRes.data.status)
          if (requestRes.data.status == '2') {
            wx.showToast({
              title: requestRes.data.msg,
              icon: 'none',
              during: 2000
            })
          } else {
            wx.reLaunch({
              url: '/pages/trans/trans'
            })
          }

        },
        fail: function () {
        },
        complete: function () {
        }
      })
    }

  },
  selectAvatarUrl: function (unionid) {
    var _that = this
    wx.request({
      url: common.formal + '/member/selectAvatarUrl.form',
      data: { unionid: unionid },
      method: 'get',
      success: function (json) {
        console.log(json.data.data)
        _that.setData({
          files: _that.data.files.concat(json.data.data),
          pathUrl: json.data.data
        })
      }
    })
  },
  onLoad(options) {
    console.log(options.objectId)
    var _that = this
    if (options.data != undefined) {
      let items = JSON.parse(options.data)
      console.log(items[0].avatarUrl)
      _that.setData({
        phone: items[0].phone,
        ['form.baseName']: items[0].objectName,
        ['form.email']: items[0].enterpriseEmail,
        ['form.address']: items[0].enterpriseAddr,
        ['form.position']: items[0].position,
        ['form.mechPhone']: items[0].enterprisePhone,
        ['form.mechanism']: items[0].enterpriseName,
        // files: _that.data.files.concat(items[0].avatarUrl),
        updateOrsubmit: 'update',
        baseId: items[0].objectId,
        pathUrl: items[0].avatarUrl,
        fromChange: 1,
        objectId: options.objectId,
        imageUrl: options.imageUrl
      })
    } else {
      console.log(options)
      if (options.avatarUrl != undefined) {
        _that.setData({
          // files: _that.data.files.concat(options.avatarUrl),
          pathUrl: options.avatarUrl
        })
      }
    }
    _that.initValidate()

    if (app.globalData.unionid && app.globalData.unionid != '') {
      let unionid = app.globalData.unionid;
      console.log(unionid)
      _that.setData({
        unionid: unionid
      })
      _that.selectAvatarUrl(unionid)
    } else {
      app.unionidCallback = unionid => {
        if (unionid != '') {
          _that.setData({
            unionid: unionid
          })
          _that.selectAvatarUrl(unionid)
        }
      }
    }


    // if (app.globalData.unionid == '') {
    //   app.unionidCallback = unionid => {
    //     if (unionid != ''){
    //       _that.selectAvatarUrl(unionid)
    //       _that.setData({
    //         unionid: unionid
    //       })
    //     }
    //   }
    // } else {
    //   var unionid = app.globalData.unionid
    //   if (options.unionid) {
    //     unionid = options.unionid
    //   }
    //   _that.setData({
    //     unionid: unionid
    //   })

    // }
  },
  showModal(error) {
    wx.showModal({
      content: error.msg,
      showCancel: false,
    })
  }

});
